<template>
	<view>
		<view class="session" v-for="(session,index) in sessions" :key="index" @tap="toChatRoom(session.fromId)" @longpress="deleteSession(session.fromId)">
			<view class="container">
				<view class="avatar-container">
					<image class="avatar"  :src='`http://127.0.0.1:15001/fileManager/getImageById?id=${session.avatarId}`'></image>
					<text class="unchecked" v-show="session.unchecked>0">{{session.unchecked}}</text>
				</view>
				<view class="content">
					<text class="name">{{session.nickName}}</text>
					<text class="preview">{{session.content.length<20?session.content:session.content.substr(0,20)+'···'}}</text>
				</view>
				<view class="time-container">
					<text class="time">{{showLastTime(session.time)}}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import WebSocket from '@/common/websocket.js';
	import dateUtil from 'util/date';
	import {mapGetters,mapActions} from 'vuex';
	export default {
		data() {
			return {
				// 调用时间方法
				timeNow: dateUtil.getTimeNow(),
				// 未读消息默认0
				unchecked:0,
				// 消息数组
				sessions:[],
				// 头部获取的用户id
				id:'',
			}
		},
		onNavigationBarButtonTap: (button) => {
			if(button.index==0){
				uni.navigateTo({
					url:'../other/search/search',
					animationType:'slide-in-right',
				})
			}
		},
		onShow(){
			// 监听用户发送的消息
			this.watchWebsocketMessage()
			
		},
		onLoad() {
			// 从头部获取用户id
			this.id = uni.getStorageSync('id')
			//查询商家给哪个用户发送了消息
			this.getBusinessChatRecord()
			// 监听用户发送的消息
			this.watchWebsocketMessage()
		},
		methods: {
			// 查询用户给哪些商家发送了消息
			getBusinessChatRecord(){
				this.$myRequest({
					url:'/eat-service/chatRecord/getBusinessChatRecord',
					data:{
						toId: this.id,
					}
				}).then(res=>{
					this.sessions = res.data.obj
					console.log(this.sessions)
				})
			},
			// 监听用户发送的消息
			watchWebsocketMessage(){
				this.id = uni.getStorageSync('id')
				var url = 'ws://' + '127.0.0.1:15001/dchat/' + this.id;
				url = url +'/H5'
				uni.connectSocket({
					// 建立websocket会话
						url:url,
						// 成功建立会话时
						success: res=>{
							console.log("websocket建立成功")
						},
						fail(res){
							console.log(res)
						}
				})
				//监听socket打开
				uni.onSocketOpen(()=>{
				    console.log('WebSocket连接已打开！');
				})
				
				//监听socket关闭
				uni.onSocketClose(()=>{
				    console.log('WebSocket连接已关闭！');
				})
				//监听socket消息
				uni.onSocketMessage((res)=>{
					//socket信息是字符串，需要先转成json形式再去解析内容
					let infos=JSON.parse(res.data) 
					switch(infos.type){
						// 私发给某个人时
						case 'person_message':
							this.personMessage(infos);
							break;	
						case 'pong':
							console.log("心跳保持成功") //判断消息类型是否为用来监听链接的ping，如果是则不继续执行只是控制台显示
							break;
					}
				})
			},
			// 将消息显示在消息栏中展示
			personMessage(infos){
				let index = infos.from;
				let content = infos.content;
				let msgType = infos.msgType;
				let time = infos.time;
				let toId = infos.to
				let fromId = infos.from
				let avatarId = infos.avatarId
				let nickName = infos.nickName
				let message = {
					content:content,
					msgType:msgType,
					time:time,
					toId:toId,
					fromId:fromId,
					avatarId:avatarId,
					nickName:nickName,
					unchecked:1,
				}
				if(this.sessions.length===0){
					this.sessions.push(message);
				}else{
					var a = 0
					this.sessions.forEach((item)=>{
						if(item.fromId===index){
							if(item.unchecked==undefined){
								this.$set(item,"unchecked",1)
							}else{
								item.unchecked++
							}
							item.content = content
							item.time = time
						}
						else{
							a++
							if(a>=this.sessions.length){
								this.sessions.push(message);
								console.log(this.sessions)
							}
							
						}
					})
				}
			},
			...mapActions(['sortSessionByTime','removeSession']),
			// 删除聊天会话记录
			deleteSession(fromId){
				let that = this;
				uni.showModal({
					title:'删除会话',
					confirmText:'确定',
					cancelText:'取消',
					confirmColor:'#D94B4D',
					content:'是否确认删除该人的聊天会话',
					success:function(res){
						if(res.confirm){
							console.log(that.sessions)
							for(var i =0;i<that.sessions.length;i++){
								if(that.sessions[i].fromId === fromId){
									that.sessions.splice(i,1)
								}
							}
							console.log(that.sessions)
						}
					}
				})
			},
			toGroupRoom(index){
				uni.navigateTo({
					url:'groupRoom/groupRoom?index='+index,
					animationType:'slide-in-right',
				})
			},
			//跳转到一对一的聊天室
			toChatRoom(fromId){
				uni.navigateTo({
					url:"/pages/chat/chatRoom?id=" + fromId
				})
				// 将那条数据的未读消息清空
				this.sessions.forEach((item)=>{
					if(item.fromId===fromId){
						item.unchecked=''
					}
				})
			},
			showLastTime(lastTime){
				console.log("1")
				let gap = dateUtil.TimeDifference(lastTime,dateUtil.getTimeNow());
				if(gap==0){
					let date = new Date(lastTime);
					return date.getHours()+":"+date.getMinutes();
				}
				else if(gap==1) return "昨天";
				else if(gap==2) return "前天";
				else{
					let date = new Date(lastTime);
					return (date.getMonth()+1)+"月"+date.getDate()+"日";
				}
			},
			toLogin(){
				uni.navigateTo({
					url:"../index/login"
				})
			}
		}
	}
</script>

<style scoped>
	.session{
		border-radius: 15rpx;
		/* background-color: rgb(200,199,204); */
	}
	.session :hover{
		border-radius: 15rpx;
		background-color: rgb(200,199,204); 
	}
	.container{
		width: 100%;
		display: flex;
		margin-top: 10rpx;
	}

	.unchecked{
		display: block;
		width: 40rpx; height: 40rpx;
		background-color: red; color: white;
		font-size:medium;
		text-align: center; line-height: 40rpx;
		border-radius: 50%;
		position: absolute; right: -10px; top: -10rpx;
 	}
	.avatar-container{
		position: relative;
		margin: 10rpx;
	}
	.avatar{
		width: 110rpx;
		height: 110rpx;
		border-radius: 50%;
	}
	.content{
		display: flex;
		align-items: auto;
		flex-direction: column;
		justify-content: center;
		padding-left: 10rpx;
	}
	.name{
		text-align: left;
		margin-top: 0;
		font-weight: 1000;
	}
	.preview{
		margin-bottom: 0;
		font-size: smaller;
	}
	.time-container{
		margin-left: auto;
		margin-right: 20rpx;
		display: flex;
	}
	.time{
		font-size: smaller;
		margin-top: auto;
		margin-bottom: auto;
		text-align: center;
	}
</style>
